﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CRM_SharePoint_Transports
{
    public class SharePointListReceiveTransport : BlueIntegrator.Extensibility.ReceiveTransportBase
    {
        public override void Initialise(string transportName, string portId, System.Collections.IDictionary transportParameters)
        {
            m_portId = portId;
            m_rpcf = transportParameters["__RPCF"] as BlueIntegrator.Messaging.ReceivePortConfigurationForm;
            m_dal = transportParameters["__DAL"] as BlueIntegrator.DAL.DALBase;
            m_properties = new System.Collections.Hashtable();
            m_bDelAfterProcess = !BlueIntegrator.Helpers.Conversion.ConvertToBool(transportParameters["KeepAfterProcessed"]);

            foreach (System.Collections.DictionaryEntry dent in transportParameters)
            {
                m_properties[dent.Key] = BlueIntegrator.Messaging.SettingTokenHelper.ResolveTokens(m_dal, BlueIntegrator.Helpers.Conversion.SafeGetString(dent.Value));
            }

            m_api = new SSISLib.SharePointListAPI();
        }

        bool m_bLocked = false, m_bDelAfterProcess;
        BlueIntegrator.Messaging.ReceivePortConfigurationForm m_rpcf;

        public override bool GetMessage(out System.IO.Stream messageContents, out System.Collections.IDictionary contextParameters, out object callBackContext)
        {
            contextParameters = null;
            messageContents = null;
            callBackContext = null;

            if (!m_bLocked)
                m_bLocked = m_dal.LockObject("RTL" + m_portId);

            if (!m_bLocked)
                return false;

            string paginationData = null;
            System.Xml.XmlDocument thisResult = m_api.GetData(m_properties, m_dal, ref paginationData);
            System.Xml.XmlDocument result = thisResult;

            while (paginationData != null)
            {
                thisResult = m_api.GetData(m_properties, m_dal, ref paginationData);

                foreach (System.Xml.XmlNode n in thisResult.DocumentElement.ChildNodes)
                {
                    System.Xml.XmlNode n2 = result.ImportNode(n, true);
                    result.DocumentElement.AppendChild(n2);
                }
            }

            if (result.DocumentElement.ChildNodes.Count > 0)
            {
                m_pendingResult = result;
                messageContents = new System.IO.MemoryStream();
                result.Save(messageContents);
                contextParameters = new System.Collections.Hashtable();
                return true;
            }

            return false;
        }

        public override void CommitReceivedMessage(object callBackContext, System.Collections.IDictionary contextParameters)
        {
            if (m_pendingResult != null)
            {
                if (m_bDelAfterProcess)
                {
                    foreach (System.Xml.XmlNode n in m_pendingResult.DocumentElement.ChildNodes)
                    {
                        // add Action node
                        System.Xml.XmlElement el = n.OwnerDocument.CreateElement("Action");
                        n.AppendChild(el);

                        System.Xml.XmlElement keyel = n.OwnerDocument.CreateElement("Key");
                        System.Xml.XmlAttribute keyattr = n.OwnerDocument.CreateAttribute("ID");

                        if (n.Attributes["ID"] == null)
                            throw new ApplicationException("Error - no ID field in returned data, cannot delete List item");

                        keyattr.Value = n.Attributes["ID"].Value;
                        keyel.Attributes.Append(keyattr);

                        System.Xml.XmlAttribute delAction = n.OwnerDocument.CreateAttribute("ActionType");
                        delAction.Value = "Delete";
                        el.Attributes.Append(delAction);
                        el.AppendChild(keyel);
                    }

                    m_api.WriteData(m_properties, m_pendingResult, m_dal);
                }
            }

            m_pendingResult = null;

            if (m_bLocked)
            {
                m_bLocked = false;
                m_dal.UnlockObject("RTL" + m_portId);
            }
        }

        public override bool CancelReceivedMessage(object callBackContext)
        {
            m_pendingResult = null;

            if (m_bLocked)
            {
                m_bLocked = false;
                m_dal.UnlockObject("RTL" + m_portId);
            }

            return false;
        }

        public override System.Windows.Forms.Control[] GetTabPages()
        {
            return new System.Windows.Forms.Control[] { new SharePointListTransportConfigControl(false, m_rpcf, null) };
        }

        BlueIntegrator.DAL.DALBase m_dal;
        string m_portId;
        System.Collections.Hashtable m_properties;
        System.Xml.XmlDocument m_pendingResult = null;
        SSISLib.SharePointListAPI m_api;
    }
}
